package com.fresh.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fresh.common.annotation.IgnoreAuth;
import com.fresh.entity.LeftMenuEntity;
import com.fresh.entity.UserEntity;
import com.fresh.entity.UserPermissionEntity;
import com.fresh.service.IExternalDataService;
import com.fresh.service.UserPermissionService;
import com.fresh.service.UserService;
import com.fresh.utils.Constant;
import com.fresh.utils.MD5;
import com.fresh.utils.Response;
import com.google.gson.Gson;

/**
 * 用户登录
 *
 * @author alex
 * @email gaonan.service@gmail.com
 * @date 2017-03-23 15:31
 */
@RequestMapping("/")
@Controller
public class ClientController  extends  BaseController{
	
	private static final Logger log = LoggerFactory.getLogger(ClientController.class); 
	
	@Autowired
	private  UserService  userService;
	
	@Autowired
	private IExternalDataService externalDataService;
	
	@Autowired
	private UserPermissionService userPermissionService;
	
	 /**
     * 进入登陆页面
     * @return
	 * @throws IOException 
     */
	@IgnoreAuth
	@RequestMapping(value = "index")
	public String toLogin(HttpServletRequest request,HttpServletResponse response) throws IOException  {
		
		return "/login";
	}
	
	 /**
     * 进入修改用户页面
     * @return
     */
	
	/**
     * 进入登陆页面
     * @return
	 * @throws IOException 
     */
	@IgnoreAuth
	@RequestMapping(value = "invalid")
	public void invalid(HttpServletRequest request,HttpServletResponse response) throws IOException  {
		 PrintWriter out = response.getWriter();  
	        out.println("<html>");      
	        out.println("<script>"); 
	        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
	        out.println("</script>");
	        out.println("</html>");
	}
	
	 /**
     * 进入修改用户页面
     * @return
     */
	
	@RequestMapping(value = "updateUser")
	public String updateUser()  {
		
		return "/changePassword";
	}
	
	/**
     * 跳转修用户页面
     * @return
     */
	@RequestMapping(value = "newTop")
	public String newTop()  {
		
		return "/navigationTop";
	}
	
	
	@IgnoreAuth
	@PostMapping("login")
	@ResponseBody
	public Response login(String name,String pwd, HttpServletRequest request )  {
		
		String md5Pwd = MD5.md5(pwd); 
		UserEntity entity = userService.queryObject(name, md5Pwd );
		if (entity != null ) {
			
			request.getSession().setAttribute("LOGIN_FLAG", 1); // 登录成功
			request.getSession().setAttribute("USER_ID",entity.getId() ); // 用户id
			request.getSession().setAttribute("SHOP_ID",entity.getShopId() ); // 商户id
			request.getSession().setAttribute("USER",entity ); // 商户id
			
			if (entity.getDel()==1) {
				return Response.error(0, "用户已被冻结，登录失败！");
			}
			return Response.ok();
		}else{
			return Response.error(0, "用户名或密码输入错误，请重新登录！");
		}
		
	}
	
	 /**
     * 进入首页页面
     * @return
     */
	@RequestMapping(value = "/login/antiFraud")
	public String toAntiFraud(HttpServletRequest request)  {
		return "redirect:/left";
	}
	
	
	/**
	 *  导航栏
	 *  @return
	 */
	@ResponseBody
	@RequestMapping(value = "top")
	public Response top(HttpServletRequest request) {
		
		try {
			if(request.getSession().getAttribute("USER_ID")!=null &&  !StringUtils.isEmpty(request.getSession().getAttribute("USER_ID").toString())){
				
				UserEntity user = externalDataService.queryById(request.getSession().getAttribute("USER_ID").toString());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user", user);
				return Response.ok(map);
			}
		} catch (Exception e) {
			log.error("页面账户失效:"+e);

		}

		return Response.error();
		
	
	}
	
	/**
	 *  菜单
	 *  @return
	 */
	@RequestMapping(value = "left")
	public String left(HttpServletRequest request){
		List<LeftMenuEntity> leftMenuEntityList=new ArrayList<LeftMenuEntity>();
		if(request.getSession().getAttribute("USER_ID")!=null &&  !StringUtils.isEmpty(request.getSession().getAttribute("USER_ID").toString())){
		List<UserPermissionEntity> UserPermissionList = userPermissionService.getUserPermissionByUserId(request.getSession().getAttribute("USER_ID").toString());
		Gson gson=new Gson();
		for (int i = 0; i < UserPermissionList.size(); i++) {
			UserPermissionEntity userPermissionEntity=UserPermissionList.get(i);
		
			LeftMenuEntity leftMenuEntity=new LeftMenuEntity();
			
			//服务
			if (userPermissionEntity.getType()==0) {
				if (userPermissionEntity.getPermissionId()==1) {
					
					leftMenuEntity.setMethodUrl(Constant.TOANTIFRAUD);
					leftMenuEntity.setImgAlt(Constant.ANTIFRAUD_ALT);
					leftMenuEntity.setImgUrl(Constant.ANTIFRAUD_IMG_URL);
					leftMenuEntity.setSort(1);
					leftMenuEntityList.add(leftMenuEntity);
				}
				if (userPermissionEntity.getPermissionId()==2) {
					leftMenuEntity.setMethodUrl(Constant.TOSCORECARD);
					leftMenuEntity.setImgAlt(Constant.SCORECARD_ALT);
					leftMenuEntity.setImgUrl(Constant.SCORECARD_IMG_URL);
					leftMenuEntity.setSort(2);
					leftMenuEntityList.add(leftMenuEntity);
				}
			}
			
			//菜单
			if (userPermissionEntity.getType()==1) {
				if (userPermissionEntity.getPermissionId()==1) {
					leftMenuEntity.setMethodUrl(Constant.AUTHORITY);
					leftMenuEntity.setImgAlt(Constant.AUTHORITY_ALT);
					leftMenuEntity.setImgUrl(Constant.AUTHORITY_IMG_URL);
					leftMenuEntity.setSort(3);
					leftMenuEntityList.add(leftMenuEntity);
				}
				if (userPermissionEntity.getPermissionId()==2) {
					leftMenuEntity.setMethodUrl(Constant.ORDERINFOPAGE);
					leftMenuEntity.setImgAlt(Constant.ORDERINFOPAGE_ALT);
					leftMenuEntity.setImgUrl(Constant.ORDERINFOPAGE_IMG_URL);
					leftMenuEntity.setSort(4);
					leftMenuEntityList.add(leftMenuEntity);
				}
			}
		}
		
		//左侧列表排序
		Collections.sort(leftMenuEntityList, new Comparator<LeftMenuEntity>() {  
	  
	            @Override  
	            public int compare(LeftMenuEntity o1, LeftMenuEntity o2) {  
	                if (o1.getSort() > o2.getSort()) {  
	                    return 1;  
	                }  
	                if (o1.getSort() == o2.getSort()) {  
	                    return 0;  
	                }  
	                return -1;  
	            }  
	        });
		
		request.setAttribute("leftMenuEntityList", leftMenuEntityList);
		return "/main";
		}
		return "/main";
	}
	
//	/**
//	 *  菜单
//	 *  @return
//	 */
//	@IgnoreAuth
//	@ResponseBody
//	@RequestMapping(value = "left")
//	public Response left(HttpServletRequest request){
//		UserEntity user = externalDataService.queryById(request.getSession().getAttribute("USER_ID").toString());
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("user", user);
//		return Response.ok(map);
//	}
	
	/**
     * 退出登录
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "loginout")
	public Response toLoginOut(HttpServletRequest request)  {
            log.info("退出登陆");
			request.getSession().removeAttribute("LOGIN_FLAG"); 
			request.getSession().removeAttribute("USER_ID"); // 用户id
			request.getSession().removeAttribute("SHOP_ID"); // 商户id
			request.getSession().removeAttribute("USER");
			
			return  Response.ok(); 
	}
	
	/**
     * 修改用户密码
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "updateUserByPwd")
	public Response updateUserByPwd(HttpServletRequest request,String pwd,String newPwd){
		
		UserEntity userInfo  = userService.findById(getUserId(request));
		
		if(userInfo!=null){
			
			String usrePwd=MD5.md5(pwd);
			if(	userInfo.getPwd().equals(usrePwd)){
				
				Boolean boo  = userService.updateUserByUserIdAndPwd(getUserId(request), MD5.md5(newPwd));
				if(boo){
					return Response.ok(0);
				}else{
					return Response.error(0,"修改失败");
				}
			}else{
				return Response.error(0,"原密码输入错误，请重新输入！");
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		 List<Student> list = new ArrayList<Student>();  
		  
	        // 创建3个学生对象，年龄分别是20、19、21，并将他们依次放入List中  
	        Student s1 = new Student();  
	        s1.setAge(20);  
	        s1.setUsable(true);  
	        Student s2 = new Student();  
	        s2.setAge(19);  
	        s2.setUsable(true);  
	        Student s3 = new Student();  
	        s3.setAge(21);  
	        s3.setUsable(false);  
	        list.add(s1);  
	        list.add(s2);  
	        list.add(s3);  
	  
	        System.out.println("排序前：" + list);  
	        Collections.sort(list, new Comparator<Student>() {  
	  
	            @Override  
	            public int compare(Student o1, Student o2) {  
	                // 按照学生的年龄进行升序排列  
	                if (o1.getAge() > o2.getAge()) {  
	                    return 1;  
	                }  
	                if (o1.getAge() == o2.getAge()) {  
	                    return 0;  
	                }  
	                return -1;  
	            }  
	        });  
	  
	        System.out.println("升序排序后：" + list);  
	  
	        Collections.sort(list, new Comparator<Student>() {  
	  
	            public int compare(Student o1, Student o2) {  
	  
	                // 按照学生的年龄进行降序排列  
	                if (o1.getAge() > o2.getAge()) {  
	                    return -1;  
	                }  
	                if (o1.getAge() == o2.getAge()) {  
	                    return 0;  
	                }  
	                return 1;  
	            }  
	        });  
	  
	        System.out.println("降序排序后：" + list);  
	  
	        Boolean b1 = true; // 创建Boolean对象1  
	  
	        Boolean b2 = false; // 创建Boolean对象0  
	  
	        Boolean b3 = true; // 创建Boolean对象1  
	        System.out.println(b1);  
	  
	        int i;  
	  
	        i = b1.compareTo(b2); // b1和b2进行比较    
	  
	        System.out.println(i);//1-0   
	  
	        i = b2.compareTo(b1); // b2和b1进行比较  
	  
	        System.out.println(i);//0-1  
	  
	        i = b1.compareTo(b3); // b1和b3进行比较  
	  
	        System.out.println(i);//1-1  
	    }  
	}  
	  
	class Student{    
	      
	    private int age;  
	      
	    private Boolean isUsable;  
	  
	    public int getAge() {    
	        return age;    
	    }    
	    
	    public Boolean isUsable() {  
	        return isUsable;  
	    }  
	  
	    public void setUsable(Boolean isUsable) {  
	        this.isUsable = isUsable;  
	    }  
	  
	    public void setAge(int age) {    
	        this.age = age;    
	    }    
	    @Override    
	    public String toString() {    
	        return getAge()+"";    
	    }    
}
